package com.coldlz.mmp.proxy.handlerserver;

import com.coldlz.mmp.proxy.LogUtil;
import com.coldlz.mmp.proxy.RemoteClient;
import com.coldlz.mmp.proxy.RemoteClientFactory;
import com.coldlz.mmp.proxy.UserContext;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerDirectForwardHandler extends ChannelDuplexHandler {
    private static final Logger log = LoggerFactory.getLogger(ServerDirectForwardHandler.class);
    final UserContext userContext;

    public ServerDirectForwardHandler(UserContext userContext) {
        this.userContext = userContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        if (obj instanceof ByteBuf msg) {
            RemoteClient remoteClient = RemoteClientFactory.getClient(userContext);
            ByteBuf newByte = msg.copy();
            remoteClient.writeAndFlush(newByte, (ChannelFuture future) -> {
                if (!future.isSuccess()) {
                    LogUtil.error(log, userContext, "发送消息失败", future.cause());
                }
                if (newByte.refCnt() > 0) {
                    ReferenceCountUtil.release(newByte);
                }
            });
            return;
        }
        throw new RuntimeException("类型异常");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LogUtil.info(log, userContext, "客户端断开连接 channelInactive");
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LogUtil.info(log, userContext, "客户端发生异常 exceptionCaught");
        super.exceptionCaught(ctx, cause);
    }

}
